from fastapi import HTTPException
from sqlalchemy.orm import Session

from api.model.user_model import User
from api.utils.session import with_session
from api.utils.repository_utils import paging
from api.vo.query.user_query import User_Query
from api.vo.value.user_value import UserValue


@with_session
def list(session: Session, userQo: User_Query):
    user = session.query(User)
    user, count = paging(user, userQo.page, userQo.rows)
    data = user.all()
    return data, count

@with_session
def get_by_username(session: Session, username: str):
    user= session.query(User).filter(User.username == username).first()
    if not user:
        return None
    return UserValue(id = user.id, username = user.username, pwd = user.pwd)

@with_session
def add(session: Session, user: User):
    session.add(user)
    return user

@with_session
def delete(session: Session, id: str):
    user = session.get(id)
    if not user:
        raise HTTPException(status_code=404, detail=f"id={id}的用户不存在")
    session.delete(user)
    return user

@with_session
def get(session: Session, id: str):
    db_user = session.get(id)
    if not db_user:
        raise HTTPException(status_code=404, detail=f"id={id}的用户不存在")
    return db_user


@with_session
def exist_by_username(session: Session,username: str):
    user = session.query(User).filter(User.username == username).first()
    if not user:
        return False
    return True


@with_session
def update_pwd(session: Session, user: User):
    db_user = session.get(user, user.id)
    if not db_user:
        raise HTTPException(status_code=404, detail=f"id={id}的用户不存在")
    db_user.pwd = user.pwd
    session.add(db_user)
    return user